package com.yql.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yql.dao.OrderDao;
import com.yql.entity.Goods;
import com.yql.entity.Order;
import com.yql.entity.OrderVO;
import com.yql.entity.User;
import com.yql.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderDao orderDao;
    @Override
    public PageInfo<Order> listOrder(User user, OrderVO orderVO, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Order> list = orderDao.listOrder(user,orderVO);
        return new PageInfo<>(list);
    }

    @Override
    public Order listOrderByOrderId(Long orderId) {
        return orderDao.listOrderByOrderId(orderId);
    }

    @Override
    public List<Goods> listGoodsByOrderId(Long orderId) {
        return orderDao.listGoodsByOrderId(orderId);
    }

    @Override
    public void addOrder(Order order) {
        orderDao.addOrder(order);
        //商品表处理(1.商品名称不存在添加新的商品到商品表  2.商品名称已存在则不添加到商品表)及中间表
        List<Goods> goodsList = order.getGoodsList();
        if(null!=goodsList && goodsList.size()>0){
            for (Goods goods : goodsList) {
                if(!"".equals(goods.getGoodsName())){//商品名称不为空时就操作
                    String goodsName = goods.getGoodsName();//商品名称
                    Goods goods1 = orderDao.selectGoodsByName(goodsName);
                    if(null!=goods1){//代表商品已存在,不需要添加到商品表,只需要处理订单个关系
                        orderDao.addMiddle(order,goods1,goods.getGoodsTotal());//添加中间表
                    }else{//没有该商品则需要添加该商品
                        orderDao.addGoods(goods);
                        orderDao.addMiddle(order,goods1,goods.getGoodsTotal());
                    }
                }
            }
        }
    }

    @Override
    public Integer deleteById(Long id) {
        return orderDao.deleteById(id);
    }

    @Override
    public Integer deleteMiddle(Long orderId) {
        return orderDao.deleteMiddle(orderId);
    }
}
